<?php

namespace App\Admin\Controllers;

use App\Admin\Grids\AppointViewRuleGrid;
use App\Admin\Repositories\AppointViewRuleTitle;
use App\Models\AppointViewRule;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class AppointViewRuleTitleController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AppointViewRuleTitle(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('weight');
            $grid->column('notes');
            $grid->column('rules','规则')->display('规则设置')->modal(function($model){

                return AppointViewRuleGrid::make(['rule_id'=>$this->id,'weight'=>$this->weight]);
            });
            $grid->disableFilter();
            $grid->disableFilterButton();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AppointViewRuleTitle(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('weight');
            $show->field('notes');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AppointViewRuleTitle(), function (Form $form) {
            $form->display('id');
            $form->text('title')->required();;
            $form->number('weight')->required();;
            $form->textarea('notes')->required();;
            $form->saved(function (Form $form, $result) {
                AppointViewRule::query()->where('rule_id',$form->getKey())
                    ->update(['weight'=>$form->weight]);
            });
            $form->submitted(function (Form $form) {
                $appointViewRuleTitle = \App\Models\AppointViewRuleTitle::query()
                    ->where('id','!=',$form->getKey())
                    ->where('weight',$form->weight)
                    ->first();
                if($appointViewRuleTitle){
                    return $form->response()->error('权重值已存在请修改后提交！');
                }
                // 中断后续逻辑
            });
        });
    }
}
